package com.example.work4

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.example.work4.baiduMapSDK.LocationListener
import com.example.work4.baiduMapSDK.LocationService
import androidx.core.app.ActivityCompat

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.*

import androidx.core.content.ContextCompat

import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.example.work4.common.FIN
import com.example.work4.common.FileUtil
import com.example.work4.http.ImageRetrofitImp
import com.example.work4.http.MomentRetrofitImp
import com.example.work4.http.body.MomentSaveBody
import com.example.work4.view.StatusBar
import com.example.work4.po.MyLocation


class PostMomentActivity : AppCompatActivity() ,View.OnClickListener{
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location)
        checkPermission()
        StatusBar.setStatusBarAsBlue(window)
        mListener.handler=mHandler
        locationService = LocationService(this)
        locationService?.registerListener(mListener)
        locationService?.setLocationOption(locationService!!.defaultLocationClientOption)
        locationService?.start()
        imageView=findViewById(R.id.choose_img)
        imageView!!.setOnClickListener(this)
        api.context = this
        api.handler = mHandler

    }

    var imageView:ImageView?=null

    var imgUri:Uri? =null

    val api = MomentRetrofitImp()

    var mlocation:MyLocation? = null;

    var mListener: LocationListener = LocationListener()

    var locationService: LocationService? = null

    private val permissions = arrayOf<String>(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    private val PERMISSIONS_RESULT_CODE = 121 // 自定义


    /**
     * 申请权限
     */
    private fun checkPermission() {
        // SDK版本 大于或等于23 动态申请权限
        val pl: MutableList<String> = ArrayList()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED
            ) {
                pl.add(permission)
            }
        }
        // 申请权限
        if (pl.size > 0) {
            ActivityCompat.requestPermissions(this, pl.toTypedArray(), PERMISSIONS_RESULT_CODE)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSIONS_RESULT_CODE && grantResults.size > 0) {
            // 判断 是否获得 权限
            for (i in grantResults.indices) {
                // 未得到 授权 的权限
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            permissions[i]
                        )
                    ) {
                        Log.i("WY", permissions[i] + " 未授权且不再询问")
                    } else {
                        Log.i("WY", permissions[i] + " 未授权")
                    }
                } else {
                    Log.i("WY", permissions[i] + " 已授权")
                }
            }
        }
    }

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        @SuppressLint("NotifyDataSetChanged", "CutPasteId")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    val ttt: TextView = findViewById(R.id.location)
                    mlocation= msg.obj as MyLocation
                    ttt.text=mlocation?.address
                }
                FIN.IMAGEURI->{
                    var landmark = findViewById<TextView>(R.id.location)
                    var content = findViewById<TextView>(R.id.content)
                    val body = MomentSaveBody()
                    body.imageUrl = msg.obj as String?
                    body.content = content.text.toString();
                    body.landmark = mlocation?.discrib
                    body.longitude = mlocation?.longitude
                    body.latitude = mlocation?.latitude
                    body.address = mlocation?.address
                    api.saveMoment(body)

                }
            }
        }
    };

    override fun onDestroy() {
        super.onDestroy()
        locationService!!.unregisterListener(mListener) //注销掉监听
        locationService!!.stop() //停止定位服务
    }

    fun choseImage(view: android.view.View)
    {
        val photoPickerIntent = Intent()
        photoPickerIntent.type = "image/*"
        photoPickerIntent.action = Intent.ACTION_GET_CONTENT
        photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(Intent.createChooser(photoPickerIntent, "Select:"),2)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 2){
            if(data!=null){
                imgUri = data.data
                imageView!!.setImageURI(imgUri)
            }
        }
    }



    fun handleImage(bitmap: Bitmap?) {
        imageView?.setImageBitmap(bitmap)
        //网路
    }


    fun postMyMoment(view: View){
        val path = FileUtil.uriToPath(imgUri,this);
        val api = ImageRetrofitImp()
        api.context = this
        api.handler = mHandler
        api.getUploadToken(path)
    }

//
//    val selectPhoto = registerForActivityResult(ActivityResultContracts.GetContent()){result:Uri ->
//        val bitmap= BitmapFactory.decodeStream(contentResolver.openInputStream(result))
//    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.choose_img ->{

//                selectPhoto .launch("image/*")
                val photoPickerIntent = Intent()
                photoPickerIntent.type = "image/*"
                photoPickerIntent.action = Intent.ACTION_PICK
//                photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE)
                startActivityForResult(Intent.createChooser(photoPickerIntent, "Select:"),2)
            }
        }
    }


}
